# -*- coding:utf-8 -*-
import logging
from logging.handlers import RotatingFileHandler

from flask import Flask, g, render_template
from flask_session import Session
from flask_sqlalchemy import SQLAlchemy
from flask_wtf import CSRFProtect
from flask_wtf.csrf import generate_csrf
from redis import StrictRedis

from config import config
from info.utils.fix_scheduler_runError import scheduler_init

db = SQLAlchemy()  # SQLAlchemy 是 Python 中一个通过 ORM 操作数据库的框架。


redis_store = None  # type: StrictRedis


def setup_log(configName):
    # 设置日志级别
    logging.basicConfig(level=config[configName].LOG_LEVEL)
    # 创建日志记录器，指明日志保存路径、日志文件大小、保存日志数量上限等
    fileLogHandler = RotatingFileHandler(config[configName].LOG_PATH,
                                         maxBytes=config[configName].LOG_FILE_SIZE,
                                         backupCount=config[configName].LOG_FILE_MAX_COUNT,
                                         encoding=config[configName].LOG_ENCODING)
    # 创建日志记录格式、等级、如数日志信息的文件名、行数、日志信息
    formatter = logging.Formatter("%(filename)s:%(lineno)d %(levelname)s %(message)s")
    # 为刚创建的日志记录器设置日志记录格式
    fileLogHandler.setFormatter(formatter)
    # 为全局的日志工具对象(flask app使用的)添加日志记录器
    logging.getLogger().addHandler(fileLogHandler)


def create_app(configName):
    """创建App，Flask(__name__)"""
    # 加载日志配置
    setup_log(configName)
    # 创建app对象
    app = Flask(__name__)
    # 加载配置
    # app.config.from_file()
    app.config.from_object(config[configName])
    # 初始化数据库
    db.init_app(app)
    # 初始化redis存储对象
    global redis_store
    redis_store = StrictRedis(host=config[configName].REDIS_HOST,
                              port=config[configName].REDIS_PORT,
                              password=config[configName].REDIS_PASSWORD,
                              decode_responses=True)
    # 开启CSRF保护
    CSRFProtect(app)
    # 设置session存储位置
    Session(app)
    # 初始化定时器
    scheduler_init(app)

    from info.utils.common import do_index_class
    app.add_template_filter(do_index_class, "index_class")

    # 设置csrf_token
    @app.after_request
    def after_request(response):
        csrfToken = generate_csrf()
        response.set_cookie("csrf_token", csrfToken)
        return response

    # 注册蓝图
    from info.modules.index import index_blu
    app.register_blueprint(index_blu)

    from info.modules.passport import passport_blu
    app.register_blueprint(passport_blu)

    from info.modules.news import news_blu
    app.register_blueprint(news_blu)

    from info.modules.profile import profile_blu
    app.register_blueprint(profile_blu)

    from info.modules.admin import admin_blu
    app.register_blueprint(admin_blu)

    from info.modules.file import file_blu
    app.register_blueprint(file_blu)

    from info.utils.common import get_user_info

    @app.errorhandler(404)
    @get_user_info
    def page_not_found(e):
        """404统一处理"""
        user = g.user
        data = {
            "user": user.to_dict() if user else None
        }
        return render_template("news/404.html", data=data)

    return app
